You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
Example 3:
Input: matrix = [[1]]
Output: [[1]]
Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]
Constraints:
因題目為rotate by 90 degrees,所以我由the last row之 first column開始,從下向上取,
取完的一個column,即為rotate後的row
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n):
ans = []
for j in range(n - 1, -1, -1):
ans.append(matrix[j][i])
matrix.append(ans)
del matrix[0:2]
後來看其他人的solution,看到一些不錯的方法
像是分為兩部分,先將 matrix transpose後,再對each row進行reflect
是一個可以更直接想到的方法!!
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Constraints:
建一個list放一個第一次出現的element,將nums內的elements和list比較,如沒有則append進去,如已在內則remove
class Solution(object):
def singleNumber(self, nums):
ans = []
for n in nums:
if n in ans:
ans.remove(n)
else:
ans.append(n)
return(ans[0])
所花費的時間和memory都太多了,看了其他討論區的solution
有以下兩種酷酷的
第一個:
def singleNumber2(self, nums):
res = 0
for num in nums:
res ^= num
return res
第二個:
def singleNumber3(self, nums):
return 2*sum(set(nums))-sum(nums)
給大家參考參考!!
以上報告完畢
明天見